<?php

namespace App\Api\Dao;

use App\Exceptions\DaoException;
use App\Helpers\Lib\WechatMini;
use App\Helpers\ResponseEnum;
use App\Models\TongUser;
use App\Models\TongUserMonthMoney;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTAuth;

class UserDao extends BaseDao
{
    /**
     * 自动执行用户的自动升级
     * @return void
     */
    public static function UserUpgrade()
    {
        TongUser::query()->whereIn('identity_id',[3,4,5,6])->chunk(100,function($user){
            foreach ($user as $item){
                $user_id = $item['id'];
                    //瞳小店升级健康管
                    $c_ids = getUserZAndJ($user_id);
                    $t_num = TongUser::query()->whereIn('id',$c_ids)->where('identity_id',3)->count();
                    if($t_num>=10){
                        //升级健康馆
                        TongUser::query()->where('id', $user_id)->update(['identity_id' => 4]);
                        updateUserIdentity($user_id, 4);
                    }
                    //升级区县
                    $z = TongUser::query()->where('p_id',$user_id)->pluck('id')->toArray();
                    $z_num = TongUser::query()->whereIn('id',$z)->where('identity_id',4)->count();
                    //$c_ids = getUserZAndJ($user_id);
                    $c_j_num = TongUser::query()->whereIn('id',$c_ids)->where('identity_id',30)->count();
                    if($z_num>=3 or $c_j_num>=30){
                        TongUser::query()->where('id', $user_id)->update(['identity_id' => 5]);
                        updateUserIdentity($user_id, 5);
                    }
                    //升级市代
                    $quxian_res = TongUser::query()->whereIn('id',$z)->where('identity_id',5)->pluck('id')->toArray();
                    if(!empty($quxian_res) && count($quxian_res)>=3){
                        $next_res = TongUser::query()->whereIn('id',$quxian_res)->where('identity_id',4)->groupBy('p_id')->count();
                        if($next_res>=3){
                            TongUser::query()->where('id', $user_id)->update(['identity_id' => 6]);
                            updateUserIdentity($user_id, 6);
                        }
                    }
                    //升级合伙人
                $quxian_res = TongUser::query()->whereIn('id',$z)->where('identity_id',6)->pluck('id')->toArray();
                if(!empty($quxian_res) && count($quxian_res)>=3){
                    $next_res = TongUser::query()->whereIn('id',$quxian_res)->where('identity_id',5)->groupBy('p_id')->count();
                    if($next_res>=3){
                        TongUser::query()->where('id', $user_id)->update(['identity_id' => 7]);
                        updateUserIdentity($user_id, 7);
                    }
                }

            }
        });
    }

    /**
     * @param $params
     * @return string
     * @throws DaoException
     */
    public function user_register($params){
        unset($params['check_password']);
        if(checkIsHasField($params,'sms_code')){
            unset($params['sms_code']);
        }
        $query = TongUser::query();
        $pInfo = $query->where('share_code',$params['share_code'])->first();
        $params['p_id']=$pInfo['id'];
        //生成邀请码
        $params['share_code'] = createShareCode();
        //生成用户的openid
        $res = $query->create($params);
        if(!$res){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'注册失败');
        }
        //所有的父级
        $this->updateChildInfo($res->id,$pInfo,$res->id);
        //更新3级父级
        //$this->updateThreeChildInfo($res->id,$pInfo,$res->id,3);
        //更新用户用户的关系
        addRedisUserData(['id'=>$res->id,'p_id'=>$pInfo['id'],'identity_id'=>0,'is_real_store'=>-1]);
        $token = getToken($res->id);
        return $token;
    }




    /**
     * 修改父级
     * @param $id
     * @param $pidInfo
     * @param $zc_id
     * @param $level
     * @return true
     */
    public function updateThreeChildInfo($id, $pidInfo, $zc_id,$level)
    {

        //  修改父级团队ID
        if (!empty($pidInfo['three_child_id'])) {
            $child_id = $pidInfo['three_child_id'] . ',' . $zc_id;
        } else {
            $child_id = $zc_id;
        }

        TongUser::query()->where('id', $pidInfo['id'])->update(['three_child_id' => $child_id]);
        if ($pidInfo['p_id'] != 0 && $level>1) {
            $pInfo = TongUser::query()->where('id', $pidInfo['p_id'])->first(['id','p_id','three_child_id']);
            $level = $level-1;
            $this->updateThreeChildInfo($pInfo['id'], $pInfo, $zc_id,$level);
        }
        return true;
    }

    /**
     * 关联用户邀请关系
     * @param $id
     * @param $pidInfo
     * @param $zc_id
     * @return true
     */
    public function updateChildInfo($id, $pidInfo, $zc_id)
    {
        //  修改父级团队ID
        if (!empty($pidInfo['child_id'])) {
            $child_id = $pidInfo['child_id'] . ',' . $zc_id;
        } else {
            $child_id = $zc_id;
        }

        TongUser::query()->where('id', $pidInfo['id'])->update(['child_id' => $child_id]);
        if ($pidInfo['p_id'] != 0) {
            $pInfo = TongUser::query()->where('id', $pidInfo['p_id'])->first(['id','p_id','child_id']);
            $this->updateChildInfo($pInfo['id'], $pInfo, $zc_id);
        }
        return true;
    }


    /**
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder
     */
    function getBuildQuery($data)
    {
        // TODO: Implement getBuildQuery() method.
        $query = TongUser::query();
        if(checkIsHasField($data,'id')){
            $query->where('id',$data['id']);
        }
        if(checkIsHasField($data,'p_id')){
            $query->where('p_id',$data['p_id']);
        }
        //手机号
        if(checkIsHasField($data,'mobile')){
            $query->where('mobile',$data['mobile']);
        }
        //账号
        if(checkIsHasField($data,'account')){
            $query->where('account',$data['account']);
        }
        return $query;
    }

    /**
     * 获取个人信息11
     * @param array $array
     * @return array
     */
    public function get_user(array $array)
    {
        $query = $this->getBuildQuery($array);

        $user_info = $query->first()->toArray();
        $user_info['jisuan'] = userBaifenbi($user_info);
        //$user_info['child_month_order'] = get_child_order_num($user_info['id']);
        if(empty($user_info['head_img'])){
            $user_info['head_img'] = config('app.url').'/storage/images/user_default.jpg';
        }


        return $user_info;
    }

    /**
     * @param array $data
     * @return mixed
     * @throws DaoException
     */
    public function userLogin(array $data)
    {
        if($data['type']==1){
            $result = $this->getBuildQuery(['mobile'=>$data['mobile']])->first();
            if(!$result){
                throw new DaoException(ResponseEnum::HTTP_ERROR,'账号或密码错误');
            }
            if($result['password']!=$data['password']){
                throw new DaoException(ResponseEnum::HTTP_ERROR,'账号或密码错误');
            }
        }else{
            $result = $this->getBuildQuery(['mobile'=>$data['mobile']])->first();
            if(!$result){
                throw new DaoException(ResponseEnum::HTTP_ERROR,'账号不存在');
            }
            if($data['code']!=8888){
                throw new DaoException(ResponseEnum::HTTP_ERROR,'验证码错误');
            }
        }
        if(config('app.is_local')==false){
            $openid = WechatMini::getOpenId($data['code']);
            if($result['openid']!=$openid){
                TongUser::query()->where('id',$result['id'])->update(['openid'=>$openid]);
            }
        }
        $token = getToken($result['id']);
        return $token;

    }

    /**
     * 设置支付密码
     * @param array $data
     * @return true
     */
    public function setPayPassword(array $data)
    {
        $result = TongUser::query()->where('id',$data['u_id'])->update(['pay_password'=>$data['pay_password']]);
        if(!$result){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'设置失败');
        }
        return true;
    }

    /**
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|void
     */
    public function getMobileInfo(array $data)
    {
        return $this->getBuildQuery(['mobile'=>$data['to_mobile']])->first();
    }

    /**
     * @param array $data
     * @return mixed
     * @throws DaoException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getUserSharePic(array $data)
    {
        return WechatMini::getMiniPic($data);
    }

    /**
     * 获取我的好友（直推用户）
     * @param array $data
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getChildUser(array $data)
    {
        $user_list = $this->getBuildQuery(['p_id'=>$data['u_id']])->paginate($data['pageSize']);
        $lists = $user_list->items();
        foreach ($lists as $key => &$item) {
            //$item['share_count'] = getUserShareCount($item['id']);
            $item['share_count'] = getUserShareCount($item['id']);
            //$item['child_month_order'] = get_child_order_num($item['id']);
            if(empty($item['head_img'])){
                $item['head_img'] = config('app.url').'/storage/images/user_default.jpg';
            }
        }
        return $user_list;

//        ->each(function($item,$key){
//            //$item['share_count'] = getUserShareCount($item['id']);
//            $item['share_count'] = getUserShareCount($item->id);
//            if(empty($item['head_img'])){
//                $item['head_img'] = config('app.url').'/storage/images/user_default.jpg';
//            }
//
//        });
    }

    /**
     * 获取我得朋友圈（我下面的全部用户 除去直推用户）
     * @param array $data
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getAllChildUser(array $data)
    {
        //获取用户信息
        $user_info = TongUser::query()->where('id',$data['u_id'])->first();
        $zhi_query = $this->getBuildQuery(['p_id'=>$data['u_id']]);
        $zhi_ids = [];

        if($zhi_query->exists()){
            $zhi_ids = $zhi_query->pluck('id')->toArray();
        }
        $all_ids = [];
        if(!empty($user_info['child_id'])){
            $all_ids = explode(',',$user_info['child_id']);
        }
        if(!$all_ids){
            return [];
        }
        $res_ids = array_intersect($all_ids,$zhi_ids);
        $all_ids = array_diff($all_ids,$res_ids);
        $user_list = TongUser::query()->whereIn('id',$all_ids)->paginate($data['pageSize']);
        $lists = $user_list->items();
        foreach ($lists as $key => &$item) {
            //$item['share_count'] = getUserShareCount($item['id']);
            //$item['share_count'] = getUserShareCount($item['id']);
            if(empty($item['head_img'])){
                $item['head_img'] = config('app.url').'/storage/images/user_default.jpg';
            }
        }
        return $user_list;
//        return TongUser::query()->whereIn('id',$all_ids)->get()->each(function($item,$key){
//            //$item['share_count'] = getUserShareCount($item['id']);
//            if(empty($item['head_img'])){
//                $item['head_img'] = config('app.url').'/storage/images/user_default.jpg';
//            }
//        });

    }

    /**
     * 修改用户信息
     * @param array $data
     * @return int
     */
    public function updateUserInfo(array $data)
    {
        $id = $data['u_id'];
        unset($data['u_id']);
        if(empty($data)){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'更新失败');
        }
        $result = TongUser::query()->where('id',$id)->update($data);
        if(!$result){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'更新失败');
        }
        return $result;
    }

    /**
     * 获取好友的详情
     * @param array $data
     * @return array
     */
    public function getFriendUserInfo(array $data)
    {
        $friend_info = $this->getBuildQuery(['id'=>$data['friend_id']])->first()->toArray();
        $friend_info['share_count'] = getUserShareCount($friend_info['id']);
        //获取好友的直推人
        //$zhi_user = getZhiUser($friend_info['id']);
        //$zhi_user_ids = array_column($zhi_user,'id');
        //dd(count($zhi_user_ids));
        //$res = userBaifenbi($friend_info);
        //$friend_info['jisuan'] = $res;
        $friend_info['head_img'] = config('app.url').'/storage/images/user_default.jpg';
        return $friend_info;
    }

    /**
     * @param array $data
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getChildUserTwo(array $data)
    {
        $user_list = $this->getBuildQuery(['p_id'=>$data['friend_id']])->paginate($data['pageSize']);
        $lists = $user_list->items();
        foreach ($lists as $key => &$item) {
            //$item['share_count'] = getUserShareCount($item['id']);
            $item['share_count'] = getUserShareCount($item['id']);
            if(empty($item['head_img'])){
                $item['head_img'] = config('app.url').'/storage/images/user_default.jpg';
            }
        }
        return $user_list;
    }


    /**
     * 每个月执行一次
     * @return void
     */
    public static function user_copy(){
        // 本月结束时间
        $lastDayOfMonth = date('Y-m-t 23:59');
        if(date('Y-m-d H:i')!=$lastDayOfMonth){
            return;
        }
        $all_user_data = [];
        TongUser::query()->each(function ($item) use(&$all_user_data){
            $all_user_data[] = [
                'u_id'=>$item['id'],
                'child_month_order'=>$item['child_month_order'],
                'p_id'=>$item['p_id'],
                'status'=>1,
                'identity_id'=>$item['identity_id'],
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time()),
            ];
        });
        //将用户业绩复制出来
        TongUserMonthMoney::query()->insert($all_user_data);
        //将用户的业绩归0
        TongUser::query()->update(['child_month_order'=>0]);
    }

    public function getAllJianUser(array $data)
    {
        $user_info = TongUser::query()->where('id',$data['u_id'])->first();
        $zhi_query = $this->getBuildQuery(['p_id'=>$data['u_id']]);
        $zhi_ids = [];

        if(!$zhi_query->exists()){
            //$zhi_ids = $zhi_query->pluck('id')->toArray();
            //如果没有直推用户直接返回空
            return [];
        }
        //如果有直推的用户接着获取直推用户下的间推用户
        $zhi_ids = $zhi_query->pluck('id')->toArray();

        $user_list = TongUser::query()->whereIn('p_id',$zhi_ids)->paginate($data['pageSize']);
        $lists = $user_list->items();
        foreach ($lists as $key => &$item) {
            //$item['share_count'] = getUserShareCount($item['id']);
            //$item['share_count'] = getUserShareCount($item['id']);
            if(empty($item['head_img'])){
                $item['head_img'] = config('app.url').'/storage/images/user_default.jpg';
            }
        }
        return $user_list;
    }

}
